package mystia.lorelei.app.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Encrypt {
    public static String sha512(String origin) {
        byte[] bytes = origin.getBytes(StandardCharsets.UTF_8);
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("SHA-512");
            messageDigest.update(bytes);
            byte[] digest = messageDigest.digest();
            String result = byteArrayToHexString(digest);
            return result.toUpperCase();
        } catch (NoSuchAlgorithmException ignored) {
            // 这个异常一定不会发生
        }
        // 不可能返回null
        return null;
    }

    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            String temp = Integer.toHexString(b & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                builder.append("0");
            }
            builder.append(temp);
        }
        return builder.toString();
    }
}
